package com.itheima.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.mapper.ProductMapper;
import com.itheima.mapper.SalesItemsMapper;
import com.itheima.mapper.SalesMapper;
import com.itheima.pojo.PageBean;
import com.itheima.pojo.Sales;
import com.itheima.pojo.SalesItems;
import com.itheima.pojo.SalesQueryParam;
import com.itheima.service.SalesService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;

/**
 * @author 3shy.cn
 * @description SalesServiceImpl
 */

@Service
public class SalesServiceImpl implements SalesService {
    @Autowired
    private SalesMapper salesMapper;
    @Autowired
    private SalesItemsMapper salesItemMapper;
    @Autowired
    private ProductMapper productMapper;


    @Override
    public PageBean page(SalesQueryParam param) {
        PageHelper.startPage(param.getPage(), param.getPageSize());

        //2. 执行查询
        Page<Sales> p = (Page<Sales>) salesMapper.page(param);

        //3. 封装结果
        return new PageBean(p.getTotal(), p.getResult());
    }


    @Transactional(rollbackFor = {Exception.class})
    @Override
    public void save(Sales sales) {
        sales.setSaleTime(LocalDateTime.now());
        List<SalesItems> salesItems = sales.getSalesItems();

        if (!CollectionUtils.isEmpty(salesItems)) {
            BigDecimal sum = salesItems.stream()
                    .map(salesItem -> {
                        BigDecimal total = salesItem.getPrice().multiply(new BigDecimal(salesItem.getNum()));
                        salesItem.setTotal(total);
                        productMapper.addNumById(salesItem.getProductId(), -salesItem.getNum());
                        return total;
                    })
                    .reduce(BigDecimal.ZERO, BigDecimal::add);
            sales.setPrice(sum); //总金额 和 总积分
//            todo 增加积分 增加提成
        }

        salesMapper.insert(sales);
        //3. 保存员工的工作经历信息 - 批量
        Integer salesId = sales.getId();

        if (!CollectionUtils.isEmpty(salesItems)) {
            salesItems.forEach(salesItem -> salesItem.setSalesId(salesId));
            salesItemMapper.insertBatch(salesItems);
        }
    }


    @Transactional
    @Override
    public void deleteByIds(List<Integer> ids) {
        //1. 根据ID批量删除员工基本信息
        salesMapper.deleteByIds(ids);

        //2. 根据员工的ID批量删除员工的工作经历信息
        salesItemMapper.deleteBySalesIds(ids);
    }


@Transactional
@Override
public void update(Sales sales) {
    // 更新销售记录
    salesMapper.updateById(sales);
    // 根据销售ID删除旧的销售项信息
    salesItemMapper.deleteBySalesIds(Arrays.asList(sales.getId()));
    // 获取销售项列表
    List<SalesItems> salesItems = sales.getSalesItems();
    // 如果销售项列表不为空，计算总价并插入新的销售项
    if (!CollectionUtils.isEmpty(salesItems)) {
        // 计算总价并设置每个销售项的总价
        BigDecimal sum = salesItems.stream()
            .map(salesItem -> {
                salesItem.setSalesId(sales.getId()); // 设置销售项的销售ID
                BigDecimal total = salesItem.getPrice().multiply(new BigDecimal(salesItem.getNum()));
                salesItem.setTotal(total); // 设置销售项的总价
                    productMapper.addNumById(salesItem.getProductId(), -salesItem.getNum());
                return total;
            })
            .reduce(BigDecimal.ZERO, BigDecimal::add); // 累加所有销售项的总价
        // 设置销售记录的总价
        sales.setPrice(sum);
        // 插入新的销售项
        salesItemMapper.insertBatch(salesItems);
    }
}

    @Override
    public Sales getInfo(Integer id) {
        return salesMapper.getById(id);
    }
}
